<%@ include file="/WEB-INF/common/taglibs.jsp"%>
<script type="text/javascript" src="${supr}/js/supr-theme/jquery-ui-timepicker-addon.js"></script>

<div class="row-fluid">
    <div class="span12">
        <div class="box closed">
            <div class="blue title">
                <h4><span>Advanced Search</span></h4>
                <a href="#" class="minimize">Minimize</a>
            </div>
            <div id="advancedSearch" class="content"></div>
        </div>
    </div>
</div>

<div class="row-fluid">
	<div class="span12">
		<div class="box gradient">
			<div class="blue title">
				<h4><span>Event Log</span></h4>
               <a href="#" class="minimize">Minimize</a>
			</div>
			<div class="content noPad clearfix">
				<table class="responsive dynamicTable display table table-bordered">
				<thead><tr>
					<th>Event Type</th>
					<th>Date Created</th>
					<th>Content</th>
					<th>Log Level</th>
					<th>By User</th>
				</tr></thead>
				</table>
			</div>
		</div>
	</div>
</div>
                                        
<script>
$(document).ready(function() {
	var oTable = $('.dynamicTable').dataTable( {
		"sPaginationType": "full_numbers",
		"bJQueryUI": false,
		"bAutoWidth": false,
		"bLengthChange": true,
		"bFilter": false,
		"aaSorting": [[ 1, "desc" ]], //sort by 'createTime'
		"fnInitComplete": function(oSettings, json) {},
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": "eventlog!listJson.action",
		"fnServerData": function ( sUrl, aoData, fnCallback, oSettings ) {
			var echo =  aoData[0].value;
			oSettings.jqXHR = $.ajax( {
				"url":  sUrl,
				"data": new QueryData(aoData),
				"success": function (json) {
					json = new DataTableForm(json, echo);
					if ( json.sError ) {
						oSettings.oApi._fnLog( oSettings, 0, json.sError );
					}
					
					$(oSettings.oInstance).trigger('xhr', [oSettings, json]);
					fnCallback( json );
				},
				"dataType": "json",
				"cache": false,
				"type": oSettings.sServerMethod,
				"error": function (xhr, error, thrown) {
					if ( error == "parsererror" ) {
						oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from "+
							"server could not be parsed. This is caused by a JSON formatting error." );
					}
				}
			} );
		},
	} );

	$("#advancedSearch").append(formRow("Event Type", filterEventType()))
			.append(formRow("Event Level", filterEventLevel()))
			.append(formRow("Username", filterUsername()))
			.append(formRow("From", filterFrom()))
			.append(formRow("To", filterTo()))
			.append(formRow("", filterButton()))
	
	$("#advFilterBtn").click(function() { 
		oTable.fnDraw(); 
	});
	
	$('.styled').uniform();

} );

function formRow(label, obj){
	var formRow = $("<div>").addClass("form-row row-fluid");
	var spanDiv = $("<div>").addClass("span10").appendTo(formRow);
	var rowDiv = $("<div>").addClass("row-fluid").appendTo(spanDiv);
	$("<label>").addClass("form-label span4").html(label).appendTo(rowDiv);
	obj.appendTo(rowDiv);
	return formRow;
}

function filterButton(){
	return $("<button>").attr({
		"id": "advFilterBtn"
	}).addClass("btn btn-info").html("Advanced Search");
}

function filterEventType(){
	 var filterDiv = $("<div>").addClass("span8");
	 var searchSelect = $("<select>").attr("id","filterEventType").addClass("styled").appendTo(filterDiv);
	 $("<option>").attr("value", "").html("All Event Type").appendTo(searchSelect);
	 $.each(allEventType(), function(index, value){
	 	$("<option>").attr("value", value).html(value).appendTo(searchSelect);	
	 });
	 return filterDiv;
}

function filterEventLevel(){
	 var filterDiv = $("<div>").addClass("span8 controls");
	 var searchSelect = $("<select>").attr("id","filterEventLevel").addClass("styled").appendTo(filterDiv);
	 $("<option>").attr("value", "").addClass("search_init").html("All Log Level").appendTo(searchSelect);
	 $.each(allEventLevel(), function(index, value){
	 	$("<option>").attr("value", value).addClass("search_init").html(value).appendTo(searchSelect);	
	 });
	 return filterDiv;
}

function filterUsername(){
	 var filterDiv = $("<div>").addClass("span8 controls");
	 $("<input>").attr({
			"id":"filterUsername",
			"placeHolder": "Username"
	 }).addClass("  text")
	 .appendTo(filterDiv);
	 return filterDiv;
}

function filterFrom(){
	 var filterDiv = $("<div>").addClass("span8 controls");
	 $("<input>").attr({
			"id":"filterFrom",
			"placeHolder": "From"
	 }).addClass("  text").datetimepicker({dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm:ss',showSecond: true})
	 .appendTo(filterDiv);
	 return filterDiv;
}

function filterTo(){
	 var filterDiv = $("<div>").addClass("span8 controls");
	 $("<input>").attr({
			"id":"filterTo",
			"placeHolder": "To"
	 }).addClass("  text").datetimepicker({dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm:ss',showSecond: true})
	 .appendTo(filterDiv);
	 return filterDiv;
}

function allEventType(){
	var result = new Array; 
	<c:set var="allEventType" value="${requestScope.allEventType}" />
	<c:if test="${allEventType!=null}">
	<c:forEach var="eventType" items="${allEventType}">
		result.push('${eventType.code}');
	</c:forEach>
	</c:if>
	return result; 
}

function allEventLevel(){
	var result = new Array; 
	<c:set var="allEventLevel" value="${requestScope.allEventLevel}" />
	<c:if test="${allEventLevel!=null}">
	<c:forEach var="eventLevel" items="${allEventLevel}">
		result.push('${eventLevel.code}');
	</c:forEach>
	</c:if>
	return result; 
}

var columnHeader = ['eventType','createTime','content','logLevel','username']; 
var QueryData = function (aoData) {
	//sorting
 	var sortColn = aoData[10].value;
 	var sortOrder = aoData[11].value;
 	var sortOrderBy = columnHeader[sortColn];
 	
	//page
    var iDisplayStart = aoData[3].value;
    var iDisplayLength = aoData[4].value;
    var pageNo = parseInt(iDisplayStart / iDisplayLength, 10) + 1;
    
    //search    
    var sEventType = $("#filterEventType").val();
    var sEventLevel = $("#filterEventLevel").val();
    var sUsername = $("#filterUsername").val();
    var sFrom = $("#filterFrom").val();
    var sTo = $("#filterTo").val();

    var filters = new Array();
    if((sEventType != null && sEventType.length>0)){
        filters.push('{"field":"eventType","op":"eq","data":"' + sEventType + '"}');
    }

    if((sEventLevel != null && sEventLevel.length>0)){
        filters.push('{"field":"logLevel","op":"eq","data":"' + sEventLevel + '"}');
    }

    if((sUsername != null && sUsername.length>0)){
        filters.push('{"field":"username","op":"cn","data":"' + sUsername + '"}');
    }

    if((sFrom != null && sFrom.length>0)){
        filters.push('{"field":"createTime","op":"ge","data":"' + sFrom + '"}');
    }
    
    if((sTo != null && sTo.length>0)){
        filters.push('{"field":"createTime","op":"le","data":"' + sTo + '"}');
    }

    var rules = "";
    $.each(filters, function (index, value) {
        rules += value + ",";
    });
    rules = rules.substring(0, rules.length - 1);

    return {
        "page.pageNo": pageNo,
        "page.pageSize": iDisplayLength,
        "page.order": sortOrder,
        "page.orderBy": sortOrderBy,
        "filters": '{"groupOp":"AND","rules":[' + rules + ']}'
    };
}

var DataTableForm = function(json,echo){
	var dataArray = new Array();
	for(var i=0; i< json.result.length; i++){
	 	var subArray = new Array();
	  	subArray.push(json.result[i].eventType);
		subArray.push(json.result[i].createTime);
		subArray.push(json.result[i].content);
		subArray.push(json.result[i].logLevel);
		subArray.push(json.result[i].username);
		dataArray.push(subArray);
	}
	return {
		sEcho: echo,
		iTotalRecords: json.totalCount, 
		iTotalDisplayRecords: json.totalCount,
		aaData: dataArray
	};
}

</script>